<?php
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
?>
<script>
require([
    'jquery',
    "uiRegistry",
    'Magento_Ui/js/modal/alert',
    'prototype'
], function(jQuery, registry, alert) {

//<![CDATA[
function refreshCouponCodesGrid(grid, gridMassAction, transport) {
    grid.reload();
    gridMassAction.unselectAll();
}

function generateCouponCodes(idPrefix, generateUrl, grid) {
    $(idPrefix + 'information_fieldset').removeClassName('ignore-validate');
    var validationResult = $(idPrefix + 'information_fieldset').select('input',
            'select', 'textarea').collect( function(elm) {
        return jQuery.validator.validateElement(elm);
    }).all();
    $(idPrefix + 'information_fieldset').addClassName('ignore-validate');

    if (!validationResult) {
        return;
    }
    var elements = $(idPrefix + 'information_fieldset').select('input', 'select', 'textarea');

    elements = elements.concat(
        $$('#rule_uses_per_coupon'),
        $$('#rule_uses_per_customer'),
        $$('#rule_to_date')
    );

    var params = Form.serializeElements(elements, true);
    params.form_key = FORM_KEY;
    if ($$('#'+idPrefix + 'information_fieldset .messages')) {
        $$('#'+idPrefix + 'information_fieldset .messages')[0].update();
    }
    if ($('messages')) {
        $('messages').update();
    }
    var couponCodesGrid = eval(grid);
    new Ajax.Request(generateUrl, {
        parameters :params,
        method :'post',
        onComplete : function (transport, param){
            var response = false;
            if (transport && transport.responseText) {
                try {
                    response = JSON.parse(transport.responseText);
                } catch (e) {
                    console.warn('An error occured while parsing response');
                }
            }
            if (couponCodesGrid) {
                couponCodesGrid.reload();
            }
            if (response && response.messages) {
                if ($$('#'+idPrefix + 'information_fieldset .messages')) {
                    $$('#'+idPrefix + 'information_fieldset .messages')[0].update(response.messages);
                } else if ($('messages')) {
                    $('messages').update(response.messages);
                }
            }
            if (response && response.error) {
                alert({
                    content: response.error
                });
            }
        }
    });
}

window.generateCouponCodes = generateCouponCodes;
window.refreshCouponCodesGrid = refreshCouponCodesGrid;
});
</script>
